<template>
  <view class="container">
    <!-- 页面头部 -->
    <view class="page-header">
      <text class="page-title">员工打卡</text>
    </view>

    <!-- 环境错误提示 -->
    <view v-if="!isUniAppEnv" class="env-error">
      <text class="error-icon">⚠️</text>
      <text class="error-text">当前环境不支持uni-app API，请在小程序或App中使用</text>
    </view>

    <view v-else>
      <!-- 位置信息 -->
      <view class="location-info">
        <text class="location-name">{{ currentLocation.location_name || '获取中...' }}</text>
        <text class="location-status" :class="locationStatusClass">{{ locationStatusText }}</text>
      </view>

      <!-- 地图组件 -->
      <view class="map-container">
        <view v-if="mapError" class="map-error">
          <text class="error-icon">⚠️</text>
          <text class="error-text">{{ mapErrorMsg }}</text>
        </view>
        <map
            v-else
            id="attendanceMap"
            :longitude="currentLocation.longitude || 116.397128"
            :latitude="currentLocation.latitude || 39.916527"
            :scale="18"
            :markers="markers"
            :show-location="true"
            style="width: 100%; height: 400rpx;"
            @error="handleMapError"></map>
      </view>

      <!-- 打卡记录 -->
      <view class="attendance-info">
        <view class="today-record" v-if="todayRecord">
          <text class="record-title">今日打卡记录</text>
          <view class="record-item">
            <text class="record-label">上班打卡:</text>
            <text class="record-time">{{ formatTime(todayRecord.check_in_time) || '未打卡' }}</text>
          </view>
          <view class="record-item">
            <text class="record-label">下班打卡:</text>
            <text class="record-time">{{ formatTime(todayRecord.check_out_time) || '未打卡' }}</text>
          </view>
        </view>
      </view>

      <!-- 打卡按钮 -->
      <view class="action-buttons">
        <button
            class="primary-btn"
            :class="{ 'disabled-btn': !canCheckIn }"
            :disabled="!canCheckIn"
            @click="checkIn">
          {{ checkInButtonText }}
        </button>
      </view>
    </view>

    <!-- 加载遮罩 -->
    <view class="loading-mask" v-if="loading">
      <view class="loading-content">
        <text class="loading-text">正在处理...</text>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      currentLocation: {},
      locationStatus: 'loading', // valid, invalid, loading, error
      markers: [],
      todayRecord: null,
      loading: false,
      locationAuthorized: true,
      isUniAppEnv: typeof uni !== 'undefined' && typeof uni.getLocation === 'function',
      mapError: false,
      mapErrorMsg: '',
      permissionDenied: false // 新增：权限被拒绝标志
    }
  },
  computed: {
    // 位置状态文本
    locationStatusText() {
      switch(this.locationStatus) {
        case 'valid': return '位置有效，可以打卡';
        case 'invalid': return '不在打卡范围内';
        case 'loading': return '正在获取位置...';
        case 'error': return this.permissionDenied ? '位置权限被拒绝' : '获取位置失败';
        default: return '';
      }
    },

    // 位置状态样式
    locationStatusClass() {
      switch(this.locationStatus) {
        case 'valid': return 'status-valid';
        case 'invalid': return 'status-invalid';
        case 'loading': return 'status-loading';
        case 'error': return 'status-error';
        default: return '';
      }
    },

    // 打卡按钮文本
    checkInButtonText() {
      if (!this.todayRecord) return '上班打卡';
      if (this.todayRecord.check_in_time && !this.todayRecord.check_out_time) return '下班打卡';
      return '今日打卡已完成';
    },

    // 是否可以打卡
    canCheckIn() {
      if (!this.isUniAppEnv || !this.locationAuthorized || this.permissionDenied) return false;
      if (this.loading || this.locationStatus !== 'valid') return false;

      return !this.todayRecord || (this.todayRecord.check_in_time && !this.todayRecord.check_out_time);
    }
  },
  onLoad() {
    if (!this.isUniAppEnv) {
      this.locationStatus = 'error'
      return
    }

    this.loadAttendanceRecord()
    this.loadNearestLocation()
  },
  methods: {
    // 加载最近的打卡位置
    loadNearestLocation() {
      if (!this.isUniAppEnv) return

      this.locationStatus = 'loading'
      this.permissionDenied = false

      // 直接尝试获取位置，捕获权限错误
      uni.getLocation({
        type: 'wgs84',
        success: (res) => {
          this.getLocationAndValidate(res)
        },
        fail: (err) => {
          console.error('获取位置失败:', err)
          this.loading = false

          // 处理权限被拒绝的情况
          if (err.errMsg && err.errMsg.includes('auth deny') || err.errMsg.includes('deny')) {
            this.permissionDenied = true
            this.locationStatus = 'error'
            this.locationAuthorized = false

            // 提示用户手动开启权限
            uni.showModal({
              title: '权限申请',
              content: '打卡功能需要获取您的位置信息，请在设置中开启位置权限',
              confirmText: '去设置',
              success: (res) => {
                if (res.confirm) {
                  uni.openSetting()
                }
              }
            })
          } else {
            // 处理其他错误
            this.locationStatus = 'error'
          }
        }
      })
    },

    // 获取位置并验证
    getLocationAndValidate(position) {
      if (!this.isUniAppEnv) return

      this.loading = true

      // 模拟从服务器获取最近的打卡位置
      setTimeout(() => {
        // 模拟服务器返回的最近打卡点
        const mockLocation = {
          id: 1,
          location_name: '总部办公室',
          latitude: position.latitude,
          longitude: position.longitude,
          radius: 100, // 100米范围内有效
          location_type: 'office'
        }

        this.currentLocation = mockLocation
        this.updateMapMarkers()

        // 模拟位置验证结果
        // 实际项目中应调用API验证位置
        this.locationStatus = 'valid'

        this.loading = false
      }, 800)
    },

    // 更新地图标记
    updateMapMarkers() {
      if (!this.currentLocation.latitude || !this.currentLocation.longitude) return

      this.markers = [
        {
          id: 1,
          latitude: this.currentLocation.latitude,
          longitude: this.currentLocation.longitude,
          title: this.currentLocation.location_name,
          iconPath: '/static/map-marker.png', // 自定义标记图标
          width: 30,
          height: 30
        }
      ]
    },

    // 加载今日打卡记录
    loadAttendanceRecord() {
      // 模拟从服务器获取今日打卡记录
      setTimeout(() => {
        // 模拟今日已有上班打卡记录
        const now = new Date()
        const morningTime = new Date(now)
        morningTime.setHours(9, 30, 0)

        // 模拟不同状态
        if (Math.random() > 0.5) {
          this.todayRecord = {
            id: 1,
            employee_id: 1001,
            check_in_time: morningTime.toISOString(),
            check_out_time: null
          }
        } else if (Math.random() > 0.7) {
          const afternoonTime = new Date(now)
          afternoonTime.setHours(18, 15, 0)

          this.todayRecord = {
            id: 1,
            employee_id: 1001,
            check_in_time: morningTime.toISOString(),
            check_out_time: afternoonTime.toISOString()
          }
        }

        // 实际项目中应调用API获取记录
        /*
        uni.request({
          url: '/api/attendance/today-record',
          method: 'GET',
          success: (response) => {
            if (response.data.code === 200) {
              this.todayRecord = response.data.data
            }
          }
        })
        */
      }, 500)
    },

    // 打卡操作
    checkIn() {
      if (!this.canCheckIn) return

      this.loading = true

      // 模拟打卡请求
      setTimeout(() => {
        const now = new Date()

        if (!this.todayRecord) {
          // 上班打卡
          this.todayRecord = {
            id: Math.floor(Math.random() * 10000),
            employee_id: 1001,
            check_in_time: now.toISOString(),
            check_out_time: null
          }

          uni.showToast({
            title: '上班打卡成功',
            icon: 'success'
          })
        } else if (this.todayRecord.check_in_time && !this.todayRecord.check_out_time) {
          // 下班打卡
          this.todayRecord.check_out_time = now.toISOString()

          uni.showToast({
            title: '下班打卡成功',
            icon: 'success'
          })
        }

        // 实际项目中应调用API提交打卡
        /*
        uni.request({
          url: '/api/attendance/check-in',
          method: 'POST',
          data: {
            location_id: this.currentLocation.id,
            type: this.todayRecord ? 'check_out' : 'check_in'
          },
          success: (response) => {
            if (response.data.code === 200) {
              this.loadAttendanceRecord()
              uni.showToast({
                title: this.todayRecord ? '下班打卡成功' : '上班打卡成功',
                icon: 'success'
              })
            } else {
              uni.showToast({
                title: response.data.message || '打卡失败',
                icon: 'none'
              })
            }
          },
          fail: () => {
            uni.showToast({
              title: '网络错误，请重试',
              icon: 'none'
            })
          },
          complete: () => {
            this.loading = false
          }
        })
        */

        this.loading = false
      }, 800)
    },

    // 格式化时间
    formatTime(timeStr) {
      if (!timeStr) return ''

      const date = new Date(timeStr)
      const hours = date.getHours().toString().padStart(2, '0')
      const minutes = date.getMinutes().toString().padStart(2, '0')

      return `${hours}:${minutes}`
    },

    // 处理地图错误
    handleMapError(e) {
      console.error('地图组件错误:', e)
      this.mapError = true

      // 根据错误类型显示不同的提示
      if (e.detail && e.detail.errMsg && e.detail.errMsg.includes('key')) {
        this.mapErrorMsg = '地图密钥未配置，请检查manifest.json'
      } else {
        this.mapErrorMsg = '地图加载失败，请稍后重试'
      }
    }
  }
}
</script>

<style>
/* 样式保持不变 */
.container {
  padding: 30rpx;
  background-color: #f8f8f8;
  min-height: 100vh;
}

.page-header {
  padding: 20rpx 0;
  border-bottom: 1rpx solid #eee;
}

.page-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  text-align: center;
}

.env-error {
  margin: 20rpx 0;
  padding: 20rpx;
  background-color: #fff1f0;
  color: #ff4d4f;
  border-radius: 12rpx;
  display: flex;
  align-items: center;
}

.location-info {
  padding: 20rpx 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.location-name {
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
}

.location-status {
  font-size: 26rpx;
  padding: 6rpx 16rpx;
  border-radius: 30rpx;
}

.status-valid {
  background-color: #e6ffed;
  color: #52c41a;
}

.status-invalid {
  background-color: #fff1f0;
  color: #ff4d4f;
}

.status-loading {
  background-color: #f5f5f5;
  color: #8c8c8c;
}

.status-error {
  background-color: #fff1f0;
  color: #ff4d4f;
}

.map-container {
  margin: 20rpx 0;
  border-radius: 12rpx;
  overflow: hidden;
  background-color: #fff;
  padding: 10rpx;
}

.map-error {
  height: 400rpx;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: #f5f5f5;
  border-radius: 12rpx;
}

.error-icon {
  font-size: 48rpx;
  color: #ff4d4f;
  margin-bottom: 20rpx;
}

.error-text {
  font-size: 28rpx;
  color: #666;
  text-align: center;
  padding: 0 40rpx;
}

.attendance-info {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 20rpx;
  margin-top: 20rpx;
}

.today-record {
  display: flex;
  flex-direction: column;
}

.record-title {
  font-size: 28rpx;
  font-weight: 500;
  color: #333;
  margin-bottom: 16rpx;
}

.record-item {
  display: flex;
  align-items: center;
  margin-bottom: 10rpx;
}

.record-label {
  font-size: 26rpx;
  color: #666;
  width: 160rpx;
}

.record-time {
  font-size: 28rpx;
  color: #333;
}

.action-buttons {
  margin-top: 60rpx;
  padding: 0 30rpx;
}

.primary-btn {
  width: 100%;
  height: 88rpx;
  line-height: 88rpx;
  border-radius: 44rpx;
  font-size: 32rpx;
  background-color: #1890ff;
  color: #fff;
  border: none;
}

.disabled-btn {
  background-color: #a8c7e7;
  color: #e6f7ff;
  cursor: not-allowed;
}

.loading-mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 999;
}

.loading-content {
  background-color: #fff;
  padding: 40rpx 60rpx;
  border-radius: 12rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.loading-text {
  font-size: 28rpx;
  color: #333;
  margin-top: 20rpx;
}
</style>